package com.stone.sys.action;

/**
 * 角色管理
 * <pre>
 * @author：JZ
 * @since:2010/02/10
 * </pre>
 */
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import com.opensymphony.xwork2.Action;
import com.stone.para.IConstant;
import com.stone.sys.pojo.TRole;
import com.stone.sys.pojo.TUser;
import com.stone.sys.service.RoleService;
import com.stone.utils.JsonUtils;

import frm.ssh.action.BaseAction;
import frm.ssh.exception.AppException;

public class RoleAction extends BaseAction {

	private static final long serialVersionUID = 865527685459140622L;

	private RoleService roleService;
	
	// 实体用于修改
	private TRole entity = new TRole();
	
	// 删除时用标示
	private String id;
	
	// 角色对应菜单
	private String checkedMenuID;
	
	// 用户授权时状态1：授权；0：取消授权
	private String flagSQ;
	
	/**
	 * 初次进入角色页面
	 * @return
	 * @throws AppException
	 */	
	public String initRole() throws IOException  {
		return Action.SUCCESS;
	}
	
	/**
	 * 查询用户菜单
	 * @return
	 * @throws AppException
	 */	
	@SuppressWarnings("unchecked")
	public void getRoleList() throws IOException  {
		
		String hql = "r.id as id , r.name as text,'" + super.getContextPath() + "/images/user_suit.png' as icon" ;

		// 查询数据
		List<HashMap<String,String>> list = roleService.getListByDHql(
							hql,
							"",//条件
							null,
							" order by r.id", 
							" TRole r");
		
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < list.size(); i++) {
			
			sb.append("{");
			sb.append("  id: '" + String.valueOf(((HashMap<String,String>)list.get(i)).get("id")) + "',");
			sb.append("  text: '" + ((HashMap<String,String>)list.get(i)).get("text") + "',");
			sb.append("  icon:'"+ super.getContextPath() + "/images/user_suit.png',");
			sb.append("  qtip: '" + ((HashMap<String,String>)list.get(i)).get("text") + "',");
			sb.append("  leaf:true");
			sb.append("},");
		}

		if (sb.toString().endsWith(",")) {
			sb = sb.deleteCharAt(sb.length() - 1);
		}

		String strTree = "[" + sb.toString() + "]";
	
	    super.getResponse().getWriter().print(strTree);
	}

	/**
	 * 查询角色菜单
	 * @return
	 * @throws AppException
	 */	
	@SuppressWarnings("unchecked")
	public void getMenu() throws Exception, AppException {
		
		// 全部的菜单（不包括按钮）
		List<HashMap<String,Object>> listAllMenu;
		
		if (id == null || "0".equals(id)) {
		
				listAllMenu = roleService.getListByDHql(
											"m.id as id , m.title as text, m.qtip as qtip, m.parentID as parentID,m.iconCls as iconCls",
											"",//条件
											null,
											" order by m.parentID, m.sortId", 
											" TMenu m");

		} else {
		
				// 修改的时候需要查询出对应角色的菜单ID
				listAllMenu = roleService.getListByDHql(
						"m.id as id , m.title as text, m.qtip as qtip, m.parentID as parentID,m.iconCls as iconCls,"
						+ "(case when (select count(rm.id) from TRoleMenu rm where rm.menuId = m.id and rm.roleId =" + id + ") > 0 then true else false end) as checked" ,
						"",//条件
						null,
						" order by m.parentID, m.sortId", 
						" TMenu m");

		}

        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(listAllMenu, jsonConfig);
        
        super.getResponse().getWriter().print(json.toString());
	}

	/**
	 * 新建或修改一条记录
	 * @return
	 * @throws AppException
	 */	
	public void save() throws IOException  {
		
		// 保存
		this.roleService.save(entity,checkedMenuID);
		super.getResponse().getWriter().print("{success:true,msg:'保存成功！'}");
		
	}
	
	/**
	 * 给用户授权
	 * @return
	 * @throws AppException
	 */	
	public void saveUserRole() throws IOException  {
	
		// 保存 id 角色ID checkedMenuID：用户ID
		this.roleService.saveUserRole(id,checkedMenuID,flagSQ);
		
		if ("1".equals(flagSQ)) {
			super.getResponse().getWriter().print("{success:true,msg:'授权成功！'}");
		} else {
			super.getResponse().getWriter().print("{success:true,msg:'取消授权成功！'}");			
		}
	}

	/**
	 * 删除一条或多条记录
	 * @return
	 * @throws AppException
	 */	
	public void delete() throws IOException  {
		
		//long count = this.roleService.getTotalByDHql("roleId = '" + this.id + "'", null, "TUserRole");
		
		//if (count > 0) {
		//	super.getResponse().getWriter().print("{success:true,msg:'该角色下有用户不能删除。'}");
		//} else {
			this.roleService.delete(Long.parseLong(id));
			super.getResponse().getWriter().print("{success:true,msg:'删除成功。'}");
		//}

	}
	
	/**
	 * 验证
	 * @return
	 * @throws AppException
	 * @throws IOException 
	 */
	public void check() throws Exception {
		
		String out = "{}";
		
		String rolecode = super.getRequest().getParameter("rolecode");
		
		// 密码验证
		if (rolecode != null) {
			
			// 修改密码时验证密码
			long count = roleService.getTotalByDHql(
					"rolecode = ?" , 
					new Object[]{rolecode},
					"TRole");
			
			
			if (count > 0) {
				out = "{msg:'角色代号已经存在请重新输入！'}";
			}
		}
		
		super.getResponse().getWriter().print(out);
		
	}

	/**
	 * 查询一条记录
	 * @return
	 * @throws AppException
	 */	
	public void find()  throws IOException  {
		
		TRole role  = (TRole) roleService.findById(Long.parseLong(id), TRole.class.getName());
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {"users"}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON((role != null? role : new TRole()), jsonConfig);

        super.getResponse().getWriter().print(json.toString());
	}

	public void setId(String id) {
		this.id = id;
	}


	public TRole getEntity() {
		return entity;
	}

	public void setEntity(TRole entity) {
		this.entity = entity;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public String getCheckedMenuID() {
		return checkedMenuID == null ? "" : checkedMenuID;
	}


	public void setCheckedMenuID(String checkedMenuID) {
		this.checkedMenuID = checkedMenuID;
	}

	public void setFlagSQ(String flagSQ) {
		this.flagSQ = flagSQ;
	}

}
